package dijjer.io.xfer.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;

public class HTTPExceptionResponse extends HTTPResponse {

	public static final String VERSION = "$Id: HTTPExceptionResponse.java 2 2008-03-21 14:33:03Z ian.clarke $";

	private final Throwable _error;
	private ByteArrayOutputStream _out;
	private static final String _header = ""
	    + "<HTML><HEAD><TITLE>ERROR</TITLE></HEAD><BODY><PRE>";
	private static final String _footer = "</PRE></BODY></HTML>";

	public HTTPExceptionResponse(HTTPException ex) throws IOException {
		super(ex.getResponseCode(), ex.getResponseMessage(), "text/html");
		_error = ex;
		_out = new ByteArrayOutputStream();
		_out.write(getDefaultHeader());
		_out.write(ex.getMessage().getBytes());
		_error.printStackTrace(new PrintStream(_out));
		_out.write(getDefaultFooter());
	}

	public HTTPExceptionResponse(Throwable ex) throws IOException {
		super(HttpURLConnection.HTTP_INTERNAL_ERROR, "Internal Error",
			ex instanceof HTTPException ? "text/html" : "text/plain");
		_error = ex;
		_out = new ByteArrayOutputStream();
		_out.write(getDefaultHeader());
		_error.printStackTrace(new PrintStream(_out));
		_out.write(getDefaultFooter());
	}

	protected long getContentLength() {
		return _out.size();
	}

	public void writeTo(OutputStream out) throws IOException {
		out.write(_out.toByteArray());
	}

	protected static byte[] getDefaultHeader() {
		return _header.getBytes();
	}

	protected static byte[] getDefaultFooter() {
		return _footer.getBytes();
	}

}
